'''

https://music.163.com/weapi/song/enhance/player/url/v1
媒体播放的两个参数，需要解析出来
vuutv
         V9wrr33VaaDQ7JLm7WxzyGWnhTOW3nAz7kSCjfteTLTyt5A1apwMMv7cygTCs3PFirwSWVurymag3dx /aN95ConAtDCddjj6QWkej9UxOg=
authSecret
           0000019a2e9778c41e5f0a3b196e19a6


通过媒体找到地址
https://music.163.com/weapi/song/enhance/player/url/v1
?csrf_token=4517a5643843a33b85ba809724733f32
POST

里面有  地址参数：
csrf_token
            4517a5643843a33b85ba809724733f32

表单参数：
params
         HCv03sDbdBBbknewei0+6GxZ5hE3rCi43bcVgNA2pLuwVuBrvbbg4GrfzMZhDUM9KO/Wyon8eUoW66UjdAxqgGeqHsmzwWrMXPxMYGZF4UBYhWEDeBSsCpUhQqfTo01K3CCki4F1eGmy5rWFpcSuPHPJRl7066hrgczdbfIifbWQKPT+YMMii3lkuBUv4mo2YFPQdpl/s73+2GiGnMfkKQ==
encSecKey
           b6c0f7b00514ecb94b86edfcc326d195e966b54e53e9a1e40a65d90e319bc97f7e43447a1918b23dd50e807579c3584c7411f3711fc0ebf9b42d95ff4fa524e931066939e6714bce84af6a7e45efe403101fd85c4e68ebaf287dde044c883a322230867b5a5a5594842a18a05e69b9c5fcd1f2d96e79bcbb102c14a68b5acd62

-----------------------------------------------------------------------

       4517a5643843a33b85ba809724733f32
params
       t53HH8sGoXbd9M5h9jQurxbJPaXbYA35RXmG2RmvIvIzFLTZn3vjgC1gH1HG6DTK3dnz5khl0pJwun+lg5ejgocYwTfudZo8VZg1zhmaaXjllZCRE8hG7FbrzV45J4PUt0UHCuq7O8J2elzZqPTuQdTagzbEP0jpmoSdbryYIC++5LnTcaC2n/QWczkvSP8NcCooBT9vKLdov9SvIMyPrQ==
encSecKey
      deeb614b53aeaac4af03f2442896bcdc9912de95ac17070061bc2f9fb821253d2150f94772d07d68063ab2aa1fc7913917132a2e9b8b9300d0a04993cab318450740ae3c6ee94b0f16fa1ef16629bcdf45e4ad16bf91ef34e49648db980f53ec9c7398736424a1373951348b0e3591ad58c48212fed2ad863474490b260e67b0


 var bVA3x = window.asrsea(JSON.stringify(i4m), bsH4L(["流泪", "强"]), bsH4L(zF4J.md), bsH4L(["爱心", "女孩", "惊恐", "大笑"]));
            e4i.data = j4n.cr4v({
                params: bVA3x.encText,
                encSecKey: bVA3x.encSecKey
            })
----------------------------------------------------------------------
 ***  d:  "{\"ids\":\"[2757535734]\",\"level\":\"exhigh\",\"encodeType\":\"aac\",\"csrf_token\":\"4517a5643843a33b85ba809724733f32\"}"
     e: "010001"
     f: "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
     g: "0CoJUm6Qyw8W8jud"
------------------------------------------------------------------------
d: "{\"id\":2754946852,\"lv\":-1,\"tv\":-1,\"csrf_token\":\"4517a5643843a33b85ba809724733f32\"}"
e: "010001"
f: "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7"
g: "0CoJUm6Qyw8W8jud"
 function d(d, e, f, g) {
        var h = {}
          , i = a(16);
        return h.encText = b(d, g),
        h.encText = b(h.encText, i),
        h.encSecKey = c(i, e, f),
        h
    }


i = a(16);
 function a(a) {
        var d, e, b = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", c = "";
        for (d = 0; a > d; d += 1)
            e = Math.random() * b.length,
            e = Math.floor(e),
            c += b.charAt(e);
        return c
    }

function b(a, b) {                                       AES加密
        var c = CryptoJS.enc.Utf8.parse(b)
          , d = CryptoJS.enc.Utf8.parse("0102030405060708")
          , e = CryptoJS.enc.Utf8.parse(a)
          , f = CryptoJS.AES.encrypt(e, c, {
            iv: d,
            mode: CryptoJS.mode.CBC
        });
        return f.toString()
    }

    function c(a, b, c) {
        var d, e;
        return setMaxDigits(131),
        d = new RSAKeyPair(b,"",c),                            RSA 加密
        e = encryptedString(d, a)
    }

'''
import base64
import json
import random
import string
import subprocess
from functools import partial

import execjs

subprocess.Popen = partial(subprocess.Popen,encodings='utf-8')



from Crypto.Cipher import AES
from Crypto.Util.Padding import pad

from yige_utils.yige_request import ChromeClient
import re

class Wyydata(ChromeClient):
    # host = 'https://music.163.com/discover'
    host = 'https://music.163.com/discover/toplist'    # 榜单地址
    # host = 'https://s3.music.126.net/web/s/core_a66ed8bbbe0b2e26892addad86eb8b88.js?a66ed8bbbe0b2e26892addad86eb8b88'
    name = input("请输入歌曲名称:")
    def __init__(self):
        super().__init__()


    def rsa_encrypt(self,a:str,b:str,c:str):
        with open('./ocer.js','r',encoding='utf-8') as f:
            js_data = f.read()
        js_data +='''
        function c(a, b, c) {
            var d, e;
            return setMaxDigits(131),
            d = new RSAKeyPair(b,"",c),                        
            e = encryptedString(d, a)
        }
        '''
        js = execjs.compile(js_data)
        return js.call('c',a,b,c)

    def random_str(self,length:int=16) -> str:
        b,c = string.ascii_letters+string.digits,''
        for d in range(length):
            e = random.randint(0,len(b)-1)
            c +=b[e]
        return c
    def aes_encrypt(self,a:str,b:str):
        iv = '0102030405060708'.encode()
        AES_dict = AES.new(key=b.encode('utf-8'),mode=AES.MODE_CBC,iv=iv)
        pad_data = pad(a.encode('utf-8'),AES.block_size)
        AES_en = AES_dict.encrypt(pad_data)
        return base64.b64encode(AES_en).decode()

    def asersea(self,id_s:int):
        h,i = {},self.random_str()
        d_s = '{\"ids\":\"[%s]\",\"level\":\"exhigh\",\"encodeType\":\"aac\",\"csrf_token\":\"4517a5643843a33b85ba809724733f32\"}'%id_s
        e_s = '010001'
        f_s = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
        g_s = '0CoJUm6Qyw8W8jud'

        h['encText'] = self.aes_encrypt(d_s,g_s)
        #  h.encText = b(h.encText, i),
        h['encText'] = self.aes_encrypt(h['encText'], i)
        #         h.encSecKey = c(i, e, f),

        h['encSecKey']=self.rsa_encrypt(i,e_s,f_s)
        return h

    def get_wbe_data(self):
        res = self.send_request(f'{self.host}')
        # pattern =r'<ul class="m-cvrlst f-cb">(.*?)</ul>'
        # pattern_02 = r'<div id="toplist" class="g-bd3 g-bd3-1 f-cb">([\s\S]*?)</div>'
        pattern_02 = r'<a href="/song\?id=(\d+)">([^<]+?)</a>'
        match = re.findall(pattern_02, res.text, re.DOTALL)
        match_str = dict(match)
        new_dict = {name_s: id_s for id_s, name_s in match_str.items()}
        match_value = new_dict.get(self.name)
        # print(match_value)
        return match_value

    def vide_str(self):
        match_value = self.get_wbe_data()
        bVA3x =self.asersea(match_value)
        res = self.send_request_post(
            'https://music.163.com/weapi/song/enhance/player/url/v1',
        params=dict(
            csrf_token='4517a5643843a33b85ba809724733f32'
        ),
            data=dict(
                params= bVA3x['encText'],
                encSecKey= bVA3x['encSecKey']
            )
        )
        print(res,res.json())
        vode_res = self.send_request(res.json()['data'][0]['url'])
        with open(f'{self.name}.m4a','wb+') as fp:
            fp.write(vode_res.content)
            print('下载完毕')







if __name__ == '__main__':
    client = Wyydata()

    client.get_wbe_data()
    client.vide_str()






